﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CashFlow.Entities
{
	public class Bill
	{
		public string Id { get; set; }
		public DateTime FirstDate { get; set; }
		public DateTime? LastDate { get; set; }
		public DateTime NextDate { get; set; }
		public double Amount { get; set; }
		public int NumberOfPayments { get; set; }
		public Tenant Tenant { get; set; }
		public Account Account { get; set; }
		public Payee Payee { get; set; }
		public string PayeeName { get; set; }
		public string Details { get; set; }
		public RecurrenceBase Recurrence { get; set; }

	  public Bill()
	  {
	            
	  }

		public Bill(Tenant tenant)
		{
			Tenant = tenant;
		}

		public static Bill GetDefault(Tenant tenant)
		{
			var bill = new Bill(tenant)
			{
				//TODO: vvs p2 convert to user time zone.
				FirstDate = DateTime.UtcNow,
				NextDate = DateTime.UtcNow,
				Tenant = tenant,
				Account = Account.GetDefault(),
				Recurrence = RecurrenceBase.GetDefault()
			};
			return bill;
		}

		public override string ToString()
		{
			var result = new StringBuilder();
			result.Append("Id:").Append(Id ?? "new bill").
				Append(",FirstDate:").Append(FirstDate).
				Append(",LastDate:").Append(LastDate.HasValue ? LastDate.Value.ToString() : string.Empty).
				Append(",NextDate:").Append(NextDate).
				Append(",Amount:").Append(Amount).
				Append(",NumberOfPayments:").Append(NumberOfPayments).
				Append(",Tenant:").Append(Tenant.Id).
				Append(",Account:").Append(Account.Id).
				Append(",Payee:").Append(Payee != null ? Payee.Id : string.Empty).
				Append(",PayeeName:").Append(PayeeName.Replace(",", "_").Replace(":", "_")).
				Append(",Details:").Append(string.IsNullOrEmpty(Details) ? 
					string.Empty : 
					Details.Replace(",", "_").Replace(":", "_")).
				Append(",Recurrence:").Append(Recurrence.GetType().ToString());
			return result.ToString();
		}

		//public IEnumerable<Bill> ForDateRange(DateRange range)
		//{
		//  var dates = Recurrence.GetNextDates(range).ToList();
		//  var bills = Recurrence.
		//    GetNextDates(range).
		//    Select(b => GetCopy(this, b)).
		//    OrderByDescending(b => b.NextDate);

		//  return bills;
		//}
		//public IEnumerable<Bill> ForDateRange(DateTime date, int days)
		//{
		//  return ForDateRange(DateRange.GetRangeForDays(date, days));
		//}

		//private Bill GetCopy(Bill bill)
		//{
		//  Mapper.CreateMap<Bill, Bill>();
		//  var copy = Mapper.Map<Bill, Bill>(bill);
		//  return copy;
		//}

		//private Bill GetCopy(Bill bill, DateTime nextDate)
		//{
		//  var copy = GetCopy(bill);
		//  copy.nextDate = nextDate;
		//  return copy;
		//}

	}
}
